import 'package:flutter/material.dart';

import 'package:barcode_scan/barcode_scan.dart';
import 'package:flutter/services.dart';

class ScanPage extends StatefulWidget {
  ScanPage({Key key}) : super(key: key);

  @override
  _ScanPageState createState() => _ScanPageState();
}

class _ScanPageState extends State<ScanPage> {
  
  ScanResult scanResult;

  Future _scan() async{
    try {
      var options = ScanOptions(
        strings: {
          "cancel": '取消',
          "flash_on": '开灯',
          "flash_off": '关灯',
        },
        // restrictFormat: selectedFormats, //限制可识别的格式
        //useCamera: -1, //用于扫描的摄像机的索引,-1所用默认相机，缺省值-1
        autoEnableFlash: false, //开始扫描时启用闪光灯
        android: AndroidOptions(
          aspectTolerance: 0.5,
          useAutoFocus: true, //使用自动对焦
        ),
      );
      var result = await BarcodeScanner.scan(options: options);
      setState(() => scanResult = result);

    } on PlatformException catch(e) {
      var result = ScanResult(
        type: ResultType.Error,
        format: BarcodeFormat.unknown,
      );

      if(e.code == BarcodeScanner.cameraAccessDenied) {
        setState(() {
          result.rawContent = '用户没有授予相机权限!';
        });
      }else {
        result.rawContent = '未知的错误: $e';
      }
      setState(() {
        scanResult = result;
      });

    }
    
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      floatingActionButton: FloatingActionButton(
        child: Icon(Icons.photo_camera),
        onPressed: _scan
      ),
      appBar: AppBar(
        title: Text('扫码') 
      ), 
      body: Text(scanResult == null ? '扫码的内容' : scanResult.rawContent)
    );
  }
}